package org.greenwire.islandharvester.helper;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.greenwire.islandharvester.domain.Harvestable;

public class FilePersistentHelper {
	
	private static final Log logger = LogFactory.getLog(FilePersistentHelper.class);

	/**
	 * 安排任务之后需要记录到文件中，以免重复安排
	 * 
	 * @param type
	 * @param id
	 */
	public static void saveHarvestableId(String ownerUid, String type, String id) {
		FileWriter fw;
		File persistentFile = new File("D:\\" + ownerUid + ".txt");
		try {
			persistentFile.createNewFile();
			fw = new FileWriter(persistentFile, true);
			fw.write(type + id + ",");
			fw.flush();
		} catch (IOException e) {
			logger.error(e.getMessage(), e);
			return;
		}

		IOUtils.closeQuietly(fw);
	}

	/**
	 * 是否已安排过任务
	 * 
	 * @param harvestable
	 * @return
	 */
	public static boolean alreadyScheduled(String ownerUid, Harvestable harvestable) {
		StringBuilder sb = new StringBuilder();
		FileInputStream fis = null;
		File persistentFile = new File("D:\\" + ownerUid + ".txt");
		try {
			persistentFile.createNewFile();
			fis = new FileInputStream(persistentFile);
			byte[] buffer = new byte[1024];
			while (fis.read(buffer) != -1) {
				sb.append(new String(buffer));
			}
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			return true;
		} finally {
			IOUtils.closeQuietly(fis);
		}

		return StringUtils.contains(sb.toString(), harvestable.getType()
				+ harvestable.getId());
	}

	/**
	 * 任务执行之后需要将记录从文件中清除
	 * 
	 * @param type
	 * @param id
	 */
	public static void removeId(String ownerUid, String type, String id) {
		FileInputStream fis = null;
		FileWriter fw = null;
		File persistentFile = new File("D:\\" + ownerUid + ".txt");
		try {
			persistentFile.createNewFile();
			fis = new FileInputStream(persistentFile);
			byte[] buffer = new byte[1024];
			StringBuilder sb = new StringBuilder();
			while (fis.read(buffer) != -1) {
				sb.append(buffer);
			}

			String[] contents = sb.toString().split(",");
			StringBuilder newString = new StringBuilder();
			for (String content : contents) { // 把执行了的任务从清单中去掉
				if (!StringUtils.equals(content, type + id)) {
					newString.append(content);
				}
			}

			fw = new FileWriter("D:\\H.txt");
			fw.write(newString.toString());

		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		} finally {
			IOUtils.closeQuietly(fis);
			IOUtils.closeQuietly(fw);
		}
	}
}
